<template>
  <ul class="contextmenu">
    <li
      v-for="item in menu"
      :id="item.action || item.name"
      :key="item.action || item.name"
      class="contextmenu__item"
    >
      <div class="button" @click.stop="fnHandler(item)">
        <i v-if="icon" :class="item.icon" />
        <span>{{ item.name }}</span>
        <i
          v-if="item.children && item.children.length > 0"
          class="el-icon-arrow-right"
        />
        <context-menu
          v-if="item.children && item.children.length > 0"
          :menu="item.children"
          :icon="icon"
          :resolve="resolve"
        />
      </div>
    </li>
  </ul>
</template>

<script>
export default {

  name: 'ContextMenu',
  components: {
  },
  props: {
    // customEvent: {
    //   type: Object
    // },
    icon: {
      // 是否显示icon
      type: Boolean,
      default: true
    },
    menu: {
      // 最重要的列表，没有的话直接不显示
      type: Array,
      default() {
        return [
          // { icon: '', name: '', action: '', fn: function() {} },
          // 模板，必须有name是国际化传过来, action是作为key和action的存在, icon如果显示但不传icon的话会留空白
          // { icon: 'el-icon-view', name: '查看', action: 'view', fn: function() {} },
          { icon: 'el-icon-edit', name: '编辑', action: 'edit' },
          { icon: 'el-icon-setting', name: '设置', action: 'setting' }
          // { icon: 'el-icon-delete', name: '删除', action: 'delete' }, // 此处传入参数时记得国际化
          // { icon: 'el-icon-printer', name: '打印', action: 'print' },
        ]
      }
    },
    resolve: {
      // 点击menu按钮时执行的方法
      type: Function,
      default: function() {}
    }
    // reject: { // 不点击按钮点击其他地方关闭时执行的方法 .catch(e => {})
    //   type: Function,
    //   default: function() {}
    // }
  },
  data() {
    return {
      status: false
    }
  },
  beforeDestroy() {
    document.body.removeChild(this.$el)
  },
  mounted() {
    // 挂载后才开始计算左右，隐藏挂载后显示不会闪一下
    this.$nextTick(function() {
      this.status = true
    })
  },
  methods: {
    fnHandler(item) {
      console.log(item)
      if (item.children && item.children.length > 0) {
        return false
      }
      this.status = false
      if (item.fn) item.fn(this.customEvent)
      this.resolve(item.action)
    }
  }
}
</script>
